package com.gps.pe.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.gps.pe.base.api.PlacementEngineController;
import com.gps.pe.utility.StringUtils;

/**
 * This is Front Controller of Placement Engine
 * 
 * URL to access this - http://localhost:8080/placementengine/testRoleService
 * 
 * @author GPS
 *
 */
@SuppressWarnings("serial")
@WebServlet(name = "PlacementEngineDispatcherServlet", urlPatterns = { "/pe/*" })
public class PlacementEngineDispatcherServlet extends HttpServlet {
	private static final Logger LOGGER = Logger.getLogger(PlacementEngineDispatcherServlet.class);

	protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LOGGER.debug("doGet called for Front Controller of Placement Engine...");
		doPost(req, resp);
	}

	protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LOGGER.info("doPost called for Front Controller of Placement Engine...");

		PlacementEngineController peController = getControllerClass(req);
		String view = "/";
		if (peController != null) {
			peController.populateBean(req, resp);
			LOGGER.debug("Successfully populate bean using Front Controller...");
			peController.execute(req, resp);
			LOGGER.debug("Successfully execute business using Front Controller...");
			view = "/" + peController.resolveView(req, resp);
			LOGGER.debug("Next View [" + view + "]");
		}
		RequestDispatcher dispatcher = req.getRequestDispatcher(view);
		dispatcher.forward(req, resp);
	}

	/**
	 * Method find request controller based on URL & return new Instance
	 * 
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private PlacementEngineController getControllerClass(HttpServletRequest req) {
		PlacementEngineController placementEngineController = null;
		String url = req.getRequestURI();
		ServletContext context = req.getServletContext();
		Map<String, String> actionMappings = (Map<String, String>) context.getAttribute("actionMappings");

		if (actionMappings != null) {
			try {
				url = actionMappings.get(url);
				if (StringUtils.isStringEmpty(url)) {
					url = "com.gps.pe.web.HomePageController";
				}
				Class<?> peClass = Class.forName(url);
				if (peClass != null) {
					LOGGER.debug("Successfully found controller for URL [" + url + "]");
					placementEngineController = (PlacementEngineController) peClass.newInstance();
					LOGGER.debug("Successfully instantiated new Object of controller [" + actionMappings.get(url)
							+ "] for URL [" + url + "]");
				}

			} catch (ClassNotFoundException e) {
				LOGGER.error("Controller [" + actionMappings.get(url) + "] not found inside mapping file", e);
			} catch (InstantiationException e) {
				LOGGER.error("Problem to instantiate Controller [" + actionMappings.get(url) + "]", e);
			} catch (IllegalAccessException e) {
				LOGGER.error("Illegal Controller [" + actionMappings.get(url) + "] present inside mapping file", e);
			}
		} else {
			LOGGER.fatal("Controller mapping not found...");
		}

		return placementEngineController;
	}
}
